/**   
 * @Title: MyHttpMessageConverter.java 
 * @Package com.dragon.learn.httpmessageconverter 
 * @Description: TODO(用一句话描述该文件做什么) 
 * @author dragon   
 * @date 2018年9月3日 下午4:12:21 
 * @version V1.0   
 */
package com.dragon.learn.httpmessageconverter;

import com.dragon.learn.web.vo.MyVO;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.nio.charset.Charset;

/** 
 * @ClassName: MyHttpMessageConverter 
 * @Description: TODO(这里用一句话描述这个类的作用) 
 * @author dragon
 * @date 2018年9月3日 下午4:12:21 
 *  
 */
public class MyHttpMessageConverter extends AbstractHttpMessageConverter<MyVO> {

	    
	public MyHttpMessageConverter() {
//		 super(new MediaType("application", "json", Charset.forName("utf-8")), new MediaType("application", "*+json", Charset.forName("utf-8")));
//		super(getMediaType());
		super(new MediaType("application", "x-wisely", Charset.forName("utf-8")));
	}
	private static MediaType getMediaType() {
		MediaType mediaType = new MediaType("application", "x-wisely", Charset.forName("utf-8"));
		return mediaType;
	}
	@Override
	protected boolean supports(Class<?> clazz) {
		// 只处理 MyVO类  
		return MyVO.class.isAssignableFrom(clazz);
	}

	@Override
	protected MyVO readInternal(Class<? extends MyVO> clazz, HttpInputMessage inputMessage)throws IOException, HttpMessageNotReadableException {
		//处理请求数据
		String temp = StreamUtils.copyToString(inputMessage.getBody(), Charset.forName("UTF-8"));
		
		// 自定义数据格式，转换vo
		String[] tempArr = temp.split("-");
		
		MyVO myVO = new MyVO();
		myVO.setAge(tempArr[0]);
		myVO.setName(tempArr[1]);
		
		return myVO;
	}

	@Override
	protected void writeInternal(MyVO t, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
		//处理响应数据
		String out = "myvo:" + t.getAge() + "-" + t.getName();
		
		outputMessage.getBody().write(out.getBytes());
	}

}
